package work.sajor.wechatpush.service;

import com.alibaba.fastjson.JSONObject;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateData;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import work.sajor.wechatpush.Weather;
import work.sajor.wechatpush.util.CaiHongPi;
import work.sajor.wechatpush.util.DateUtil;


@Service
public class PusherService {
    /**
     * 测试号的appId和secret
     */
    @Value("${wechat.appId}")
    private String appId;
    @Value("${wechat.secret}")
    private String secret;
    @Value("${wechat.templateId}")
    private String templateId;
    @Value("${tian.caihongpi.key}")
    private String key;
    @Value("${target.anniversary}")
    private String anniversary;
    @Value("${target.you.birthday}")
    private String youbirthday;
    @Value("${target.me.birthday}")
    private String mebirthday;

    @Autowired
    private WeatherService weatherServiceService;

    @Autowired
    private WxMpService wxMpService;

    public void push(String openId){
        try {
        WxMpTemplateMessage templateMessage = WxMpTemplateMessage.builder()
                .toUser(openId)
                .templateId(templateId)
                .build();

           wxMpService.getTemplateMsgService().sendTemplateMsg(buildPush(templateMessage));
        } catch (Exception ignored) {
        }
    }


    /**
     * 请注意：
     * 1、测试模板的模板ID仅用于测试，不能用来给正式帐号发送模板消息
     * 2、为方便测试，测试模板可任意指定内容，但实际上正式帐号的模板消息，只能从模板库中获得
     * 3、需为正式帐号申请新增符合要求的模板，需使用正式号登录公众平台，按指引申请
     * 4、模板内容可设置参数(模板标题不可)，供接口调用时使用，参数需以{{开头，以.DATA}}结尾
     * @param templateMessage
     * @return
     */
    public WxMpTemplateMessage buildPush(WxMpTemplateMessage templateMessage){
        String now = weatherServiceService.getHZWeather().getString("now");
        /**
         * {
         *   "vis" : "23",
         *   "temp" : "27",
         *   "obsTime" : "2025-10-17T10:16+08:00",
         *   "icon" : "101",
         *   "wind360" : "135",
         *   "windDir" : "东南风",
         *   "pressure" : "1014",
         *   "feelsLike" : "29",
         *   "cloud" : "91",
         *   "precip" : "0.0",
         *   "dew" : "23",
         *   "humidity" : "72",
         *   "text" : "多云",
         *   "windSpeed" : "8",
         *   "windScale" : "2"
         * }
         */
        Weather weather =JSONObject.parseObject(now, Weather.class);
        String formattedDate = "";
        String formattedTime = "";
        String weekDay = "";
        String obsTime = weather.getObsTime();
        if (obsTime != null && !obsTime.isEmpty()) {
            try {
                // 解析原始时间格式 "2025-10-16T11:08+08:00"
                java.time.format.DateTimeFormatter formatter = java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mmXXX");
                java.time.ZonedDateTime dateTime = java.time.ZonedDateTime.parse(obsTime, formatter);

                // 格式化为 "2025年10月16日"
                formattedDate = dateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy年MM月dd日"));
                formattedTime =getTimePeriod(dateTime.getHour()) + dateTime.format(java.time.format.DateTimeFormatter.ofPattern("H点m分"));


                // 获取星期几
                String[] weekdays = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};
                weekDay = weekdays[dateTime.getDayOfWeek().getValue() - 1];
            } catch (Exception e) {
                // 如果解析失败，使用默认值
                formattedDate = "";
                weekDay = "";
            }
        }
        templateMessage.addData(new WxMpTemplateData("tianqiDay",formattedDate+" "+weekDay));
        templateMessage.addData(new WxMpTemplateData("tianqi", formattedTime+" "+weather.getText()+" "+weather.getTemp()));
        templateMessage.addData(new WxMpTemplateData("high", weather.getFeelsLike()));
        templateMessage.addData(new WxMpTemplateData("caihongpi", CaiHongPi.getCaiHongPi(key)));
        templateMessage.addData(new WxMpTemplateData("anniversary", DateUtil.getAnniversary(anniversary)+"","#FF1493"));
        templateMessage.addData(new WxMpTemplateData("youbirthday", DateUtil.daysUntilLunarDate(youbirthday)+"","#FFA500"));
        templateMessage.addData(new WxMpTemplateData("mebirthday", DateUtil.daysUntilLunarDate(mebirthday)+"","#FFA500"));
        // templateMessage.addData(new WxMpTemplateData("jinju",CaiHongPi.getJinJu()));
        String beizhu = "今天比昨天更爱你一点！";
        if(DateUtil.getAnniversary(anniversary) % 365 == 0){
            beizhu = "今天是恋爱纪念日！";
        }
        templateMessage.addData(new WxMpTemplateData("beizhu",beizhu));

        return templateMessage;
    }

    private String getTimePeriod(int hour) {
        if (hour >= 6 && hour < 12) {
            return "早上";
        } else if (hour >= 12 && hour < 18) {
            return "下午";
        } else {
            return "晚上";
        }
    }
}
